﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;
using System.Threading;

namespace GPSMSP340ProtocolListenerWindowsService
{
    // State object for reading client data asynchronously
    public class StateObject
    {
        // Client socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 512;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
    }

    public partial class GPSMSP340ProtocolListenerWindowsService : ServiceBase
    {
        public const int BufferSize = 512;

        // Thread signal.
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        private static bool IsThreadAlive = true;
        public static Thread TCPListenerThread = new Thread(StartListening);

        // Enum Field
        public enum MessageField
        {
            Command,
            Serial,
            Imei,
            TotalByte,
            Date,
            Time,
            Latitude,
            Longitude,
            GPSStatus,
            GSMSignal,
            Baterry,

        }

        public GPSMSP340ProtocolListenerWindowsService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("--- GPS Tracking Server Start Listening MSP340 V1 ---", "MSP340");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("IP: " + System.Net.Dns.GetHostName(), "MSP340");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Port: " + Properties.Settings.Default.Port.ToString(), "MSP340");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Max Connections: " + Properties.Settings.Default.MaxConnections.ToString(), "MSP340");

                IsThreadAlive = true;
                TCPListenerThread.Start();
            }
            catch (Exception ex)
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error..... Message:" + ex.Message, "MSP340");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("MSP340 Server is DOWN", "MSP340");
                this.Stop();
            }
        }

        protected override void OnStop()
        {
            IsThreadAlive = false;
            GPSTrackingDBCustom.Log.WindowsServiceLog.Warning("--- GPS Tracking Server MSP340 Is DOWN ---", "MSP340");
        }

        public static void StartListening()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, Properties.Settings.Default.Port);

            // Create a TCP/IP socket for listner.
            Socket listenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the endpoint and wait for listen for incoming connections.
            try
            {
                listenerSock.Bind(ep);
                listenerSock.Listen(Properties.Settings.Default.MaxConnections);

                while (IsThreadAlive)
                {
                    try
                    {
                        // Set the event to nonsignaled state.
                        allDone.Reset();

                        // Start an asynchronous socket to listen for connections.
                        GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Waiting for a connection MSP340 ...", "MSP340");
                        listenerSock.BeginAccept(new AsyncCallback(AcceptCallback), listenerSock);

                        // Wait until a connection is made before continuing.
                        allDone.WaitOne();
                    }
                    catch (Exception ex)
                    {
                        GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error - Waiting for a connection ... Message:" + ex.Message, "MSP340");
                        listenerSock.Shutdown(SocketShutdown.Both);
                        listenerSock.Close();
                    }

                }

            }
            catch (Exception ex)
            {
                IsThreadAlive = false;
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error..... Message:" + ex.Message, "MSP340");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("MSP340 Server is DOWN", "MSP340");
            }
        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                // Signal the main thread to continue.
                allDone.Set();

                // Get the socket that handles the client request.
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);

                // Create the state object.
                StateObject MessageDevice = new StateObject();
                MessageDevice.workSocket = handler;
                handler.BeginReceive(MessageDevice.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), MessageDevice);
            }
            catch (Exception ex)
            {
                IsThreadAlive = false;
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error..... Message:" + ex.Message, "MSP340");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("MSP340 Server is DOWN", "MSP340");                   
            }
        }

        public static int GetIndexOfMessageOf(MessageField messageField)
        {
            try
            {
                int index = 0;

                if (MessageField.Command == messageField) return index; else index += 3;
                if (MessageField.Serial == messageField) return index; else index += 3;
                if (MessageField.Imei == messageField) return index; else index += 15;
                if (MessageField.TotalByte == messageField) return index; else index += 3;
                if (MessageField.Date == messageField) return index; else index += 6;
                if (MessageField.Time == messageField) return index; else index += 6;
                if (MessageField.Latitude == messageField) return index; else index += 10;
                if (MessageField.Longitude == messageField) return index; else index += 11;
                if (MessageField.GPSStatus == messageField) return index; else index += 1;
                if (MessageField.GSMSignal == messageField) return index; else index += 2;
                if (MessageField.Baterry == messageField) return index; else index += 4;

                return index++;
            }
            catch
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Error - Get Index Parameter", "MSP340");
                return 0;
            }
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            // Retrieve the state object and the handler socket
            // from the asynchronous state object.
            StateObject MessageDevice = (StateObject)ar.AsyncState;
            Socket handler = MessageDevice.workSocket;

            // Read data from the client socket.
            int bytesRead = handler.EndReceive(ar);

            try
            {
                //No Message 
                if (bytesRead <= 0)
                {
                    GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Disconnected... gps device. No Message", "MSP340");
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();

                    return;
                }

                //Process Message Hande Held
                string Message = System.Text.UTF8Encoding.UTF8.GetString(MessageDevice.buffer).Replace("\0", "");
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Message Device: " + Message, "MSP340");

                int index = GetIndexOfMessageOf(MessageField.Command);
                string Command = Message.Substring(index, 3);

                if (Command == "#SA" || Command == "#SC")
                {

                    //Message = Message.Replace("#SA", "#SB").Replace("#SC", "#SB");                                     

                    //SendCommand(handler, System.Text.Encoding.UTF8.GetBytes(Message));

                    // Not all data received. Get more.                    
                    handler.BeginReceive(MessageDevice.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), MessageDevice);
                    return;
                }

                 //Latitudes
                index = GetIndexOfMessageOf(MessageField.Latitude);                
                string DeviceLatitude = Message.Substring(index, 9); //10 latitudes
                
                //Longitude
                index = GetIndexOfMessageOf(MessageField.Longitude);                
                string DeviceLongitude = Message.Substring(index, 10); //11 Latitudes               

                //Imei
                index = GetIndexOfMessageOf(MessageField.Imei);
                string DeviceID = Message.Substring(index, 15); //15 Imei

                //10.0553583333333, -84.441359   83333333
                //10.055651,        -84.441339


                //Convert NMEA
                //Convert Lat.
                int LatDegree = Convert.ToInt32(DeviceLatitude.Substring(0, 2));
                double LatMinute = Convert.ToDouble(DeviceLatitude.Substring(2));

                LatMinute = LatDegree + (LatMinute / 60);
                LatMinute = Math.Round(LatMinute, 6); // Fix decimal
                LatMinute = LatMinute - 0.000292; // Fix metros

                //Convert Long.
                int LongDegree = Convert.ToInt32(DeviceLongitude.Substring(0, 3));
                double LongMinute = Convert.ToDouble(DeviceLongitude.Substring(3));

                LongMinute = LongDegree + (LongMinute / 60);
                LongMinute = LongMinute * -1;
                LongMinute = Math.Round(LongMinute, 6); // fix decimal
                LongMinute = LongMinute + 0.000020; // Fix metros 


                //Insert to Database
                GPSTrackingDBV2.Entities.TrackData TrackDataEntity = new GPSTrackingDBV2.Entities.TrackData();
                try
                {
                    GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Inserting track message to database ...", "MSP340");
                    GPSTrackingDBV2.Entities.TrackDataLastLocation TrackDataLastLocationEntity = new GPSTrackingDBV2.Entities.TrackDataLastLocation();

                    TrackDataLastLocationEntity.GpsImei = TrackDataEntity.GpsImei = DeviceID;
                    TrackDataLastLocationEntity.DateTime = TrackDataEntity.DateTime = DateTime.Now;
                    TrackDataLastLocationEntity.Latitude = TrackDataEntity.Latitude = LatMinute;
                    TrackDataLastLocationEntity.Longitude = TrackDataEntity.Longitude = LongMinute;
                    TrackDataLastLocationEntity.Heading = 0;
                    TrackDataLastLocationEntity.Speed = 0;

                    GPSTrackingDBV2.Data.DataRepository.TrackDataProvider.Insert(TrackDataEntity);

                    //Update last location  
                    GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Updating last track message location to database ...", "MSP340");
                    try
                    {
                        GPSTrackingDBV2Custom.Data.DataRepository.TrackDataLastLocationProvider.UpdateOrInsert(TrackDataLastLocationEntity);
                    }
                    catch (Exception ex)
                    {
                        GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error - Updating last track message:" + ex.Message, "MSP340");
                        // Disconnect 
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }


                }
                catch (Exception ex)
                {
                    GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error - Inserting track message:" + ex.Message, "MSP340");
                    // Disconnect 
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }

                // Disconnect Hand Held                      
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Disconnected... gps device.", "MSP340");
                //Send(handler, Encoding.ASCII.GetBytes("OK"));

            }
            catch (Exception ex)
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error - Message invalid:" + ex.Message, "MSP340");
                // Disconnect Hand Held                    
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();

                //Send(handler, Encoding.ASCII.GetBytes("Message Invalid"));
            }

        }

        private static void Send(Socket handler, byte[] MessageSend)
        {
            try
            {
                // Begin sending the data to the remote device.               
                handler.BeginSend(MessageSend, 0, MessageSend.Length, 0, new AsyncCallback(SendCallback), handler);
            }
            catch (Exception ex)
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error - Send Message:" + ex.Message, "MSP340");
                // Disconnect 
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }

        private static void SendCallback(IAsyncResult ar)
        {
            // Retrieve the socket from the state object.
            Socket handler = (Socket)ar.AsyncState;
            try
            {
                // Complete sending the data to the remote device.
                //int bytesSent = handler.EndSend(ar);
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Disconnected... gps device.", "MSP340");
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();

            }
            catch (Exception ex)
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error - SendCallBack Message: " + ex.Message, "MSP340");
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }

        private static void SendCommand(Socket handler, byte[] MessageSend)
        {
            // Begin sending the data to the remote device.
            GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Command Send: " + System.Text.UTF8Encoding.UTF8.GetString(MessageSend).Replace("\0", ""), "MSP340");
            handler.BeginSend(MessageSend, 0, MessageSend.Length, 0, new AsyncCallback(SendCallbackCommand), handler);
        }

        private static void SendCallbackCommand(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket handler = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                GPSTrackingDBCustom.Log.WindowsServiceLog.Info("Command... Send " + bytesSent.ToString() + " bytes to gps device.", "MSP340");

            }
            catch (Exception ex)
            {
                GPSTrackingDBCustom.Log.WindowsServiceLog.Error("Error Command..... " + ex.Message, "TK103");
            }
        }
    }    
}
